package com.szjz.elasticsearch.eshelper.context;

import com.szjz.elasticsearch.eshelper.animation.ESEntityScan;
import com.szjz.elasticsearch.eshelper.animation.ESTable;
import com.szjz.elasticsearch.eshelper.scaner.ESScanner;
import com.szjz.elasticsearch.eshelper.service.ESService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author shibo
 * @desc 通过上下文获取 @ESEntityScan 注解内容 用于项目启动创建索引库
 * @date 2020/6/3 周三
 */

@Slf4j
@Component
public class ESApplicationContext implements ApplicationContextAware {

    @Autowired
    private ESService esService;

    /**
     * 获取所有 添加有@ESEntityScan 注解的类
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> beansWithAnnotationMap = applicationContext.getBeansWithAnnotation(ESEntityScan.class);
        if (beansWithAnnotationMap.size() == 0) {
            return;
        }
        for (Map.Entry<String, Object> value : beansWithAnnotationMap.entrySet()) {
            String[] split = value.getValue().toString().split("\\$\\$");
            Class<?> aClass = null;
            try {
                aClass = Class.forName(split[0]);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
			assert aClass != null;
			ESEntityScan esEntityScan = aClass.getDeclaredAnnotation(ESEntityScan.class);
            for (String basePackage : esEntityScan.basePackages()) {
                ESScanner.scanning(basePackage, false);
                ESScanner.getCLASSES().keySet().forEach(clazz -> {
                    try {
                        Class<?> aClass1 = Class.forName(clazz);
                        // 获取所有添加有@ESTable注解的实体类
                        if (aClass1.isAnnotationPresent(ESTable.class)) {
                            // 取消启动创建索引库
                            esService.createIndex(aClass1);
                        }
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                });
            }
        }
    }



}
